medusa-plugin-reviews-and-ratings
Version:
Medusa plugin to add product reviews and ratings functionality in the project.
65 lines (64 loc) • 2.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GET = void 0;
const medusa_1 = require("@medusajs/medusa");
const product_review_1 = require("../../../../models/product-review");
const utils_1 = require("@medusajs/utils");
const GET = async (req, res) => {
const { id: product_id } = req.params;
const { limit, page } = req.query;
const parsedLimit = parseInt(limit, 10) || 0;
const parsedPage = parseInt(page, 10) || 0;
const offset = (parsedPage - 1) * parsedLimit < 0 ? 0 : (parsedPage - 1) * parsedLimit;
const manager = req.scope.resolve("manager");
const productReviewRepo = manager.getRepository(product_review_1.ProductReview);
const productRepo = manager.getRepository(medusa_1.Product);
const product = await productRepo.findOneBy({
id: product_id,
});
if (!product) {
throw new utils_1.MedusaError(utils_1.MedusaError.Types.NOT_FOUND, "Product not found");
}
const [reviews, ratings] = await Promise.all([
productReviewRepo.find({
where: { product: { id: product_id } },
relations: ["customer", "images"],
skip: offset,
take: parsedLimit,
order: {
created_at: "DESC",
},
}),
productReviewRepo.find({
select: ["rating"],
where: { product: { id: product_id } },
}),
]);
const star_wise_data = {
star_1: { total: 0, bar_percentage: 0 },
star_2: { total: 0, bar_percentage: 0 },
star_3: { total: 0, bar_percentage: 0 },
star_4: { total: 0, bar_percentage: 0 },
star_5: { total: 0, bar_percentage: 0 },
};
ratings.forEach((rating) => {
if (rating.rating > 0)
star_wise_data[`star_${rating.rating}`].total++;
});
const total_ratings = ratings.length;
Object.entries(star_wise_data).forEach(([key, value]) => (star_wise_data[key].bar_percentage =
(value.total / total_ratings) * 100 || 0));
const average_rating = ratings.reduce((total, rating) => total + rating.rating, 0) /
total_ratings || 0;
const total_pages = Math.ceil(total_ratings / parsedLimit)
? Math.ceil(total_ratings / parsedLimit)
: 1;
return res.json({
reviews,
total_ratings,
total_pages,
average_rating,
star_wise_data,
});
};
exports.GET = GET;